package k8sconfig

import (
	v1 "github.com/shenyisyn/dbcore/pkg/apis/dbconfig/v1"
	"github.com/shenyisyn/dbcore/pkg/controllers"
	v12 "k8s.io/api/apps/v1"
	"log"
	"os"
	"sigs.k8s.io/controller-runtime/pkg/builder"
	"sigs.k8s.io/controller-runtime/pkg/handler"
	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/manager/signals"
	"sigs.k8s.io/controller-runtime/pkg/source"
)

func InitManger()  {
	logf.SetLogger(zap.New())
	mgr ,err := manager.New(K8sRestConfig(),manager.Options{
		Logger: logf.Log.WithName("dbcore"),
	})
	if err !=nil {
		log.Fatalf("启动失败 %v",err.Error())
	}

	dbconfigConfigController := controllers.NewDbConfigController()
	err = v1.SchemeBuilder.AddToScheme(mgr.GetScheme())
	if err != nil {
		log.Fatalf("启动失败 %v",err.Error())
	}
	if err=builder.ControllerManagedBy(mgr).
		For(&v1.DbConfig{}).Watches(&source.Kind{Type: &v12.Deployment{}},handler.Funcs{
			DeleteFunc: dbconfigConfigController.OnDelete,
			UpdateFunc: dbconfigConfigController.OnUpdate,
	}).
		Complete(controllers.NewDbConfigController());err!=nil{
		mgr.GetLogger().Error(err, "unable to create manager")
		os.Exit(1)
	}

	if err=mgr.Start(signals.SetupSignalHandler());err!=nil{
		mgr.GetLogger().Error(err, "unable to start manager")
		os.Exit(1)
	}
}
